//
//  MapViewController.m
//
//  SFU Pathways 2012 by UGuideUs
//
//  Created by Viswanadh Nekkanti on 16/06/2012.
//

#import "MapViewController.h"
#import "Annotation.h"
#import "PictureInFlickr.h"

@interface MapViewController() <MKMapViewDelegate>

@property (nonatomic) NSString *imagename;
@property (nonatomic) NSString *roomname;

@end

@implementation MapViewController

@synthesize textfield = _textfield;
@synthesize mapView = _mapView;
@synthesize mylocation = _mylocation;
@synthesize locationmanager = _locationmanager;
@synthesize imagename = _imagename;
@synthesize roomname = _roomname;
@synthesize errorMessage = _errorMessage;


/*  NAME:       prepareForSegue()
 *
 *  PURPOSE:    Allows another view to prepare for the sending of information from this view.
 */

- (void)prepareForSegue : (UIStoryboardSegue *)segue sender : (id)sender
{
    if ([segue.identifier isEqualToString : @"picturesetting"]) 
    { 
        NSLog(@"hi");
        [segue.destinationViewController setPicturename : _imagename];
    }
}


/*  NAME:       viewDidLoad()
 *
 *  PURPOSE:    The series of tasks that should be done when the user enters this view (or starts
 *              the application).
 */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    MKCoordinateRegion region;
    
    region.center.latitude = 49.278165;
    region.center.longitude = -122.917871;
    region.span.latitudeDelta = 0.022;
    region.span.longitudeDelta =0.02;
    
    [_mapView setRegion : region animated : YES];
    [_mapView setDelegate : self];
    _mapView.mapType = MKMapTypeStandard;
    [mapDesc setTitle: @"Map" forState:UIControlStateNormal];
    
    //change navigation bar colour
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed : 172.0/255   
                                                                        green : 04.0/255   
                                                                         blue : 08.0/255   
                                                                        alpha : 1]; 
    
    //change tab bar colour
    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed : 172.0/255 
                                                             green : 04.0/255 
                                                              blue : 08.0/255 
                                                             alpha : 1];
}


/*  NAME:       viewDidUnload()
 *
 *  PURPOSE:    The series of tasks that should be done when the user exits this view (or
 *              the application).
 */

- (void)viewDidUnload
{
    [self setMapView : nil];
    [self setMapView : nil];
    [self setMylocation : nil];
    [self setLocationmanager : nil];
    [self setLocationmanager : nil];
    [self setTextfield : nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


/*  NAME:       shouldAutorotateToInterfaceOrientation()
 *
 *  PURPOSE:    Inform the caller whether the application can be rotated along with the device
 *              or not.
 */

- (BOOL)shouldAutorotateToInterfaceOrientation : (UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}


/*  NAME:       mapView :: viewForAnnotation
 *
 *  PURPOSE:    Controls the displaying of a room annotation when the room's pin is queried.
 */

- (MKAnnotationView *) mapView : (MKMapView *) mapView viewForAnnotation : (id<MKAnnotation>)annotation
{
    MKPinAnnotationView *MyPin = [[MKPinAnnotationView alloc] initWithAnnotation : annotation 
                                                                 reuseIdentifier : @"current"];
    
    MyPin.pinColor = MKPinAnnotationColorPurple;
    
    UIButton *advertButton = [UIButton buttonWithType : UIButtonTypeDetailDisclosure];
    
    [advertButton addTarget : self action : @selector(button:) forControlEvents : UIControlEventTouchUpInside];
    NSLog(@"%@",[annotation title]);
    
    MyPin.rightCalloutAccessoryView = advertButton;
    MyPin.draggable  = NO;
    MyPin.highlighted = YES;
    MyPin.animatesDrop = TRUE;
    MyPin.canShowCallout = YES;
    
    return MyPin;
}


/*  NAME:       button()
 *
 *  PURPOSE:    ?
 */

- (void)button : (id)sender
{
    [self performSegueWithIdentifier : @"picturesetting" sender : self];
    //NSLog(@"Button action");
}


/*  NAME:       setMap()
 *              formerly setmymap()
 *
 *  PURPOSE:    Controls the background Google Maps type: that is, whether the user is seeing
 *              a standard map view, a satellite only view, or a hybrid view that overlays the
 *              standard map on top of the sattelite view.
 */

- (IBAction)setMap : (id)sender {
    
    if (_mapView.mapType == MKMapTypeStandard) {
        _mapView.mapType = MKMapTypeSatellite;
        [mapDesc setTitle: @"Sattelite" forState:UIControlStateNormal];
    }
    
    else if (_mapView.mapType == MKMapTypeSatellite) {
        _mapView.mapType = MKMapTypeHybrid;
        [mapDesc setTitle: @"Hybrid" forState:UIControlStateNormal];
    }
    
    else {
        _mapView.mapType = MKMapTypeStandard;
        [mapDesc setTitle: @"Map" forState:UIControlStateNormal];
    }
    
}


/*  NAME:       getMyLocation()
 *              formerly getmycurrentlocation()
 *
 *  PURPOSE:    Controls the activation and disabling of the phone's location service.
 */

- (IBAction)getMyLocation : (id)sender {
    
    if (_mapView.showsUserLocation) 
        _mapView.showsUserLocation = NO;
    
    else
        _mapView.showsUserLocation = YES;
    
}


/*  NAME:       searchlocation()
 *
 *  PURPOSE:    Finds the room that the user has queried for by looking through a dictionary
 *              list of most rooms on campus in the enabled buildings.
 */

- (IBAction)searchlocation : (id)sender {
    
    [self.mapView removeAnnotations : self.mapView.annotations];
    Annotation *ann = [[Annotation alloc] init];
    
    NSString *searchName;
    searchName = [_roomname stringByAppendingString : self.textfield.text];
    
    // Read in a file called nameList.ls and parse it as a list of strings.
    
    NSString* path = [[NSBundle mainBundle] pathForResource : @"nameList" ofType : @"ls"];
    NSString* content = [NSString stringWithContentsOfFile : path
                                                  encoding : NSUTF8StringEncoding
                                                     error : NULL];  
    // NSLog(@"%@", content); 
    
    NSArray *lines = [content componentsSeparatedByString : @"\n"];
    NSMutableDictionary *pictureInfo = [[NSMutableDictionary alloc] init];
    
    
    for (NSString *line in lines) {
        
        // NSLog(@"%@", line);     
        NSArray *locationInfo = [line componentsSeparatedByString : @":"];
        
        if([locationInfo count] > 1) {
            [pictureInfo setObject : [locationInfo objectAtIndex : 1] forKey : [locationInfo objectAtIndex : 0]];
        }
    
    }
    
    
    NSString *infoOfLocation = [pictureInfo objectForKey : searchName];
    
    NSLog(@"key: %@, value: %@", searchName, infoOfLocation);
    
    
    if (infoOfLocation){
        
        NSArray *infoArray = [infoOfLocation componentsSeparatedByString : @","];
    
        MKCoordinateRegion region;
        
        double mylatitude = [[infoArray objectAtIndex : 2] doubleValue];
        double mylongitude = [[infoArray objectAtIndex : 3] doubleValue];
        
        NSString *pictureTitle = [infoArray objectAtIndex : 0];
        NSString *pictureSubTitle = [infoArray objectAtIndex : 1];
        NSString *pictureName = [infoArray objectAtIndex : 4];
        
        // Part below controls location (center.*) and map zoom (*Delta).
        
        region.center.latitude = mylatitude;
        region.center.longitude = mylongitude;
        region.span.latitudeDelta = 0.001;
        region.span.longitudeDelta = 0.001;
        
        ann.title = pictureTitle;
        ann.subtitle = pictureSubTitle;
        ann.coordinate = region.center;
        
        [_mapView addAnnotation : ann];
        _imagename = pictureName;
        NSLog(@"%@", _imagename);
        
        self.textfield.text = @"";
        [_mapView setRegion : region animated : YES];
    }
    
    else {
        
        //  The error label is only visible when it cannot find a room to match. The label
        //  disappers if the user starts editing or closes the keyboard session.
        self.textfield.text = @"";
        self.errorMessage.hidden = NO;
        self.errorMessage.text = @"Room not found.";
    
    }
    
}


/*  NAME:       returnKeyboard() and backTouched()
 *              formerly retrunkeyboard()
 *
 *  PURPOSE:    Turns off the keyboard after the user presses return on it.
 *              Also turns off keyboard after user touches background.
 */

- (IBAction)returnKeyboard : (id)sender {
    [sender resignFirstResponder];
}


- (IBAction)backTouched : (id)sender {
    [self.textfield resignFirstResponder];
}

/*  NAME:       reveal() and hide()
 *
 *  PURPOSE:    Turns off the keyboard after the user presses return on it.
 */

- (IBAction)reveal
{
    if (button1.hidden) {
        button1.hidden = NO;
        button2.hidden = NO;
        button3.hidden = NO;
        button4.hidden = NO;
        button5.hidden = NO;
    }
    else
        [self hide];
    
}

- (void)hide
{
    button1.hidden = YES;
    button2.hidden = YES;
    button3.hidden = YES;
    button4.hidden = YES;
    button5.hidden = YES;
}


/*  NAME:       select*()
 *
 *  PURPOSE:    Sets the search to look for rooms in the selected building only.
 */
- (IBAction)selectAQ : (id)sender
{
    _roomname = @"aq";
    roombutton.title = @"AQ";
    [self hide];    
}

- (IBAction)selectASB : (id)sender
{
    _roomname = @"asb";
    roombutton.title = @"ASB";
    [self hide];  
}

- (IBAction)selectBLU : (id)sender
{
    _roomname = @"blu";
    roombutton.title = @"BLU";
    [self hide];  
}

- (IBAction)selectSWH : (id)sender
{
    _roomname = @"swh";
    roombutton.title = @"SWH";
    [self hide];  
}

- (IBAction)selectWMC : (id)sender
{
    _roomname = @"wmc";
    roombutton.title = @"WMC";
    [self hide];  
}


/*  NAME:       clearError()
 *
 *  PURPOSE:    Turns off the error label once user starts editing or closes keyboard.
 */

- (IBAction)clearError:(id)sender {
    self.errorMessage.text = @"";
    self.errorMessage.hidden = YES;
}

@end
